using Microsoft.AspNetCore.Mvc;
using WebRtcProject.Services;

namespace WebRtcProject.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HealthController : ControllerBase
    {
        private readonly ILogger<HealthController> _logger;
        private readonly RabbitMQService _rabbitMQService;
        private readonly ConsulService _consulService;

        public HealthController(
            ILogger<HealthController> logger, 
            RabbitMQService rabbitMQService,
            ConsulService consulService)
        {
            _logger = logger;
            _rabbitMQService = rabbitMQService;
            _consulService = consulService;
        }

        /// <summary>
        /// 健康检查端点
        /// </summary>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(new 
            { 
                status = "healthy", 
                timestamp = DateTime.UtcNow,
                version = "1.0.0",
                service = "WebRTC Signaling Server"
            });
        }

        /// <summary>
        /// 详细健康检查
        /// </summary>
        [HttpGet("detailed")]
        public async Task<IActionResult> GetDetailed()
        {
            try
            {
                // 检查RabbitMQ健康状态
                var rabbitMQHealthy = _rabbitMQService.IsConnected;

                // 检查Consul健康状态
                var consulHealthy = await _consulService.IsHealthyAsync();

                var overallHealthy = rabbitMQHealthy && consulHealthy;
                var healthStatus = overallHealthy ? "healthy" : "degraded";

                return Ok(new
                {
                    status = healthStatus,
                    timestamp = DateTime.UtcNow,
                    version = "1.0.0",
                    service = "WebRTC Signaling Server",
                    uptime = Environment.TickCount64,
                    memoryUsage = GC.GetTotalMemory(false),
                    environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
                    dependencies = new
                    {
                        rabbitmq = new
                        {
                            status = rabbitMQHealthy ? "healthy" : "unhealthy",
                            connected = rabbitMQHealthy
                        },
                        consul = new
                        {
                            status = consulHealthy ? "healthy" : "unhealthy",
                            connected = consulHealthy
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Health check failed");
                return StatusCode(503, new 
                { 
                    status = "unhealthy", 
                    error = ex.Message,
                    timestamp = DateTime.UtcNow
                });
            }
        }
    }
} 